package cn.wolfcode.cms.service.impl;

import cn.wolfcode.cms.domain.Member;
import cn.wolfcode.cms.domain.MemberSpend;
import cn.wolfcode.cms.domain.Recharge;
import cn.wolfcode.cms.mapper.MemberMapper;
import cn.wolfcode.cms.mapper.MemberSpendMapper;
import cn.wolfcode.cms.mapper.RechargeMapper;
import cn.wolfcode.cms.query.QueryObject;
import cn.wolfcode.cms.service.IRechargeService;
import cn.wolfcode.cms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class RechargeServiceImpl implements IRechargeService {

    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberSpendMapper memberSpendMapper;

    public void save(Recharge entity) {
        entity.setRechargetime(new Date());//设置操作时间
        Long op_id = entity.getOp_id();//获取操作是充值还是扣费
        Member member = memberMapper.getMenberByCardNum(entity.getCard_num());
        entity.setOldbalance(member.getBalance());//获取旧余额
        if (op_id == 13L) {//充值
            BigDecimal add = entity.getAddmoney().add(entity.getGivemoney());
            member.setBalance(member.getBalance().add(add));
            member.setIntegral(member.getIntegral() + add.intValue() / 10);
            MemberSpend memberSpend = memberSpendMapper.selectByMemberId(member.getId());
            if (memberSpend == null) {
                memberSpend = new MemberSpend();
                memberSpend.setTotalbalance(add.longValue());
                memberSpend.setTotalspend(0L);
                memberSpend.setMember(member);
                memberSpendMapper.insert(memberSpend);
            } else {

            }
        } else if (op_id == 14L) {//扣费
            entity.setPay_id(9L);
            member.setBalance(member.getBalance().subtract(entity.getSubmoney()));
            entity.setAddmoney(entity.getSubmoney());
            entity.setGivemoney(new BigDecimal("0"));
        }
        entity.setNewbalance(member.getBalance());//获取新余额
        memberMapper.updateBalanceById(member);
        rechargeMapper.insert(entity);
    }

    public List<Recharge> list() {
        return rechargeMapper.selectAll();
    }

    public Object query(QueryObject qo) {
        //查总数
        int total = rechargeMapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        //查数据
        List<Recharge> rows = rechargeMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

}
